import threading
import time

import reader_first as rf
import writer_first as wf
import fair

if __name__ == '__main__':
    idx = []
    type_list = []
    start_time = []
    continue_time = []
    error_count = 0  # 添加错误计数器

    try:
        with open('in.txt', 'r') as f:
            data = f.readlines()
            for line_num, line in enumerate(data, start=1):
                x = line.strip().split()
                if len(x) < 4:
                    print(f"警告：文件格式错误，第 {line_num} 行缺少必要的字段")
                    error_count += 1
                    continue

                try:
                    idx_value = int(x[0])
                    if idx_value < 0:
                        raise ValueError("第一列必须为非负整数")
                    type_value = x[1]
                    if type_value not in ['R', 'W']:
                        raise ValueError("第二列必须是 'R' 或 'W'")
                    start_time_value = int(x[2])
                    if start_time_value < 0:
                        raise ValueError("第三列必须为非负整数")
                    continue_time_value = int(x[3])
                    if continue_time_value < 0:
                        raise ValueError("第四列必须为非负整数")

                    idx.append(idx_value)
                    type_list.append(type_value)
                    start_time.append(start_time_value)
                    continue_time.append(continue_time_value)
                except ValueError as e:
                    print(f"错误：第 {line_num} 行数据格式错误 - {e}")
                    error_count += 1

        if error_count == 0:  # 如果没有错误行，才继续执行
            # 用户选择策略
            while True:
                opt = input("请选择策略（1-读者优先，2-写者优先，3-公平竞争）：")
                if opt in ['1', '2', '3']:
                    break  # 用户输入了有效选项，退出循环
                else:
                    print("无效输入，请重新选择。")

            start = time.time()
            threads = []

            # 根据用户选择创建线程
            if opt == '1':
                target_module = rf
            elif opt == '2':
                target_module = wf
            elif opt == '3':
                target_module = fair

            for i in range(len(type_list)):
                if type_list[i] == 'R':
                    t = threading.Thread(target=target_module.reader,
                                         args=(idx[i], continue_time[i], start, start_time[i]))
                else:
                    t = threading.Thread(target=target_module.writer,
                                         args=(idx[i], continue_time[i], start, start_time[i]))
                t.start()
                threads.append(t)

            # 等待所有线程完成
            for t in threads:
                t.join()

            print("所有任务已完成。")
        else:
            print(f"有 {error_count} 行数据格式错误，未启动线程。")

    except FileNotFoundError:
        print("错误：文件 'in.txt' 未找到")
    except Exception as e:
        print(f"发生了一个未预料的错误：{e}")